package com.ux.iot.jetlinks.service.websocket;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @author caixiaodao
 * @version 1.0
 * 功能描述
 * ping service
 * @date 2021/11/23 14:31
 */
@Slf4j
public class PingService {
    static  boolean isRun=true;
    static ExecutorService single= Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
          Thread t=  new Thread(r,"ping-thread-async");
          t.setDaemon(true);
          return t ;
        }
    });
    /**
     * 启动心跳
     */
    public static void  start(){
        single.execute(()->{
            while (isRun) {
                try {
                    Session session = SessionManager.getSingleSession();
                    if (ObjectUtil.isNotEmpty(session) && session.isOpen()) {
                        session.getAsyncRemote().sendText(new String(new byte[0]));
                    }
                    Thread.sleep(30*1000);
                } catch (Exception e) {
                    log.error("session 异常信息 {}", e.getMessage());
                }
            }
        });
    }

    /**
     * 停止心跳
     */
    public static void  stop(){
        isRun =false;
        single.shutdown();
    }
}
